import datetime
import re

import urllib3

from common import SITE
from common.utils import gen_keyword
from database.db import save_movie_list, get_categories, get_category, save_tv_list
from detail import md5
from downloader import download


def checkUpdate():
    urllib3.disable_warnings()
    try:
        check_first_page()
    except Exception as e:
        pass
    try:
        check_movies()
    except:
        pass
    try:
        check_tvs()
    except:
        pass


def check_tvs():
    url = f'{SITE}/gvod/dsj.html'
    resp = download(url)
    movies = []
    lis = resp.xpath('//div[@id="main"]/div/div[1]/ul/li')
    for li in lis:

        isRecommend = 0
        try:
            title = li.xpath('a/text()').extract()[0]
        except:
            title = li.xpath('a/font/text()').extract()[0]
            isRecommend = 1
        try:
            name = re.findall('《(.*)》', title)[0]
            if not name:
                continue
        except:
            continue
        url = li.xpath('a/@href').extract()[0]
        main_category, category_list, type = gen_keyword(title, url)
        movie_md5 = md5(url)
        if 'http' not in url:
            url = f'{SITE}/{url}'

        try:
            order = int(re.findall(r'(\d{2,8})\.html', url)[0])
        except:
            order = 0
        date = li.xpath('span/text()').extract()[0]
        date = formatDate(date)
        try:
            tip = re.findall('》(.*)', title)[0].strip()
        except:
            tip = ''
        movies.append({
            'order': order,
            'category': '/'.join(category_list),
            'date': date,
            'title': title,
            'name': name,
            'url': url,
            'isRecommend': isRecommend,
            'category_list': category_list,
            'updated': 1,
            'main_category': 'tv',
            'md5': movie_md5,
            'type': type,
            'tip':tip
        })
    save_tv_list(movies)


def check_movies():

    url = 'https://www.hao6v.tv/gvod/zx.html'
    resp = download(url)
    lis = resp.xpath('//ul[@class="list"]/li')
    lis += resp.xpath('//ul[@class="lt"]/li')
    movies = []
    for li in lis:
        movie_url = li.xpath('a/@href').extract()[0]
        movie_md5 = md5(movie_url)

        main_category, category_list, type = gen_keyword(title, movie_url)
        if 'http' not in movie_url:
            movie_url = f'https://www.hao6v.tv{movie_url}'
        try:
            title = li.xpath('a/font/text()').extract()[0]
            isRecommend = 1
        except:
            try:
                title = li.xpath('a/text()').extract()[0]
                isRecommend = 0
            except:
                continue
        for key in ['颁奖典礼', '晚会', '排行榜', '佳片推荐', '榜单', '合集', '口碑', '演唱会']:
            if key in title:
                continue
        try:
            name = re.findall('《(.*)》', title)[0]
        except:
            continue
        try:
            order = int(re.findall(r'(\d{2,8})\.html', movie_url)[0])
        except:
            order = 0
        date = li.xpath('span/text()').extract()[0]
        date = formatDate(date)
        try:
            tip = re.findall('》(.*)', title)[0].strip()
        except:
            tip = ''
        movies.append({
            'order': order,
            'category': '/'.join(category_list),
            'date': date,
            'title': title,
            'name': name,
            'url': movie_url,
            'isRecommend': isRecommend,
            'category_list': category_list,
            'updated': 1,
            'tip':tip,
            'main_category':'movie',
            'md5':movie_md5
        })
    save_movie_list(movies)


def formatDate(date):
    date = re.findall(r'(\d+)', date)
    month = int(date[0])
    day = int(date[1])
    now = datetime.datetime.now()
    curYear = now.year
    curMonth = now.month
    curDay = now.day
    if month > curMonth or (month == curMonth and day > curDay):
        year = curYear - 1
    else:
        year = curYear
    return f'{year}-{date[0]}-{date[1]}'


def check_first_page():
    url = 'https://www.hao6v.tv/'
    resp = download(url)
    # lis = resp.xpath('//ul[@class="list"]/li')
    lis = resp.xpath('//div[@class="box"]/ul[@class="lt"]/li')
    movies = []
    for li in lis:
        movie_url = li.xpath('a/@href').extract()[0]
        movie_md5 = md5(movie_url)
        if 'http' not in movie_url:
            movie_url = f'{SITE}{movie_url}'
        try:
            title = li.xpath('a/font/text()').extract()[0]
            isRecommend = 1
        except:
            try:
                title = li.xpath('a/text()').extract()[0]
                isRecommend = 0
            except:
                continue
        isNotNeed = False
        main_category, category_list, type = gen_keyword(title, movie_url)
        for key in ['颁奖典礼', '晚会', '排行榜', '佳片推荐', '榜单', '合集', '口碑', '演唱会']:
            if key in title:
                isNotNeed = True
                break
        if isNotNeed:
            continue

        try:
            name = re.findall('《(.*)》', title)[0]
        except:
            continue

        try:
            tip = re.findall('》(.*)', title)[0].strip()
        except:
            tip = ''
        try:
            order = int(re.findall(r'(\d{2,8})\.html', movie_url)[0])
        except:
            order = 0
        try:
            date = li.xpath('span/text()').extract()[0]
            date = formatDate(date)
        except:
            date = re.findall(r'\d{4}-\d{2}-\d{2}', movie_url)[0]

        movies.append({
            'order': order,
            'category': '/'.join(category_list),
            'date': date,
            'title': title,
            'name': name,
            'url': movie_url,
            'isRecommend': isRecommend,
            'category_list': category_list,
            'updated': 1,
            'tip': tip,
            'md5': movie_md5,
            'type':type,
            'main_category': main_category
        })
    save_movie_list(movies)


if __name__ == '__main__':
    checkUpdate()
